import {url} from './config'
class wescoket{
    constructor(username) {
        this.websock = {};
        this.username=username;
        this.timeout=10000;
        this.timeoutObj=null;
        this.serverTimeoutObj= null;
        this.lockReconnect = false;
    }
    initWebSocket(){ //初始化websocket
		// process.env.VUE_APP_API_BASE_URL
        const wsuri = "ws://192.168.1.110:8008/linghuo/push/609";
        // const wsuri = "ws://124.70.79.154:8008/immediatelyPush/"+this.username;
        this.websock = wx.connectSocket({
			url: wsuri,
			header:{
                'Content-Type': 'application/json'
			},
			success(){
			},
			fail(err){
				console.log('链接错误',err);
			}
		  })
        this.websock.onMessage = this.websocketonmessage;
        this.websock.onOpen = this.websocketonopen;
        this.websock.onError = this.websocketonerror;
        this.websock.onClose = this.websocketclose;
        this.websock.initWebSocket = this.initWebSocket;
        this.websock.heartCheck = this.heartCheck;
        this.websock.onSend = this.websocketonsend;
        this.websock.reconnect = this.reconnect;
        console.log(this.websock)
        console.log('开始链接')
    }
    websocketonsend(str){
        console.log('发送数据');
        this.websock.send(str)
    }
    websocketonopen(){ //连接建立之后执行send方法发送数据
        console.log('打开链接');
        this.heartCheck()
    }
    websocketonerror(e){//连接建立失败重连
        console.log('报错信息',e)
        this.initWebSocket();
    }
    websocketonmessage(e){ //数据接收
        // 接收到数据 继续检测
        this.heartCheck()
        console.log('接收数据',e.data);
      }
      websocketclose(is_initiative){  //关闭
        console.log('断开链接了，需重连');
        if(is_initiative){
            //  z主动断开 什么也不做
            this.websock.onclose();
            this.websock={};
        }else{
            // 被动断开需重连
            this.reconnect()
        }
      }
    reconnect() {
        if(this.lockReconnect) return;
        this.lockReconnect = true;
        let _this = this;
        setTimeout(function () {     //没连接上会一直重连，设置延迟避免请求过多
            _this.initWebSocket()
            _this.lockReconnect = false;
        }, 5000);
    }
    reset(){
        clearTimeout(this.timeoutObj);
        clearTimeout(this.serverTimeoutObj);
        this.heartCheck();
    }
    heartCheck () {
        //每隔几秒测试一下心跳是否在继续
            this.timeoutObj && clearTimeout(this.timeoutObj);
            this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj);
            let _this  =this;
            this.timeoutObj = setTimeout(function(){
                //这里发送一个心跳，后端收到后，返回一个心跳消息，
                console.log('发送消息，测试后台是否运行中...');
                //任意发一个消息过去，后台接收，在init()中的onmessage收到消息，说明后台没有挂掉，有心跳
                _this.websock.onsend('fuwu');
                _this.serverTimeoutObj = setTimeout(function() {
                    console.log("后台挂掉，没有心跳了....");
                    // console.log("打印websocket的地址:"+websocket);
                    _this.websock.onclose(false);
                    // createWebSocket();
                }, _this.timeout);
            }, _this.timeout)
    };
}

// exports.websocket = wescoket;
export  {
    wescoket
  }